<?php
/**
 * 员工管理
 *
 * @author 孙晓晔
 * @version $Id: User.class.php 1035 2010-03-26 05:24:59Z sunxy $s
 */

require_once(dirname(__FILE__) . '/Info.class.php');

class User extends Info {

	public $tbl = Constant::tbl_emp;

	function __construct() {
		$request['update'] = '$Date: 2009/03/06 11:35:48 $';
		$request['revision'] = '$Revision: 1.2 $';

		parent::__construct($request);
	}

	/**
	 * 预处理
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function pretreat($controller) {
		parent::pretreat($controller);
	}
	
	function layout($controller, $request) {
		$data = array(
			'前台分机' => array('cc'=>'emp.php?do=User.a', 'js'=>''),
		);

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'tab');
		return true;
	}
	
	function a($controller, $request) {
		
		$cf_ns = $this->_cf_get('6006');
		$cf_sj = $this->_cf_get('8008');
		
		$controller->assign('cf_ns', $cf_ns);
		$controller->assign('cf_sj', $cf_sj);		
		
		$controller->display($request, 'emp/user/a');
		return true;
	}
	
	function _cf_get($exten) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE exten = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp_exten, $exten);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return $row['cf'];
		}
		
		return '';
	}
	
	function aPost($controller, $request) {
		$cf_ns = $request['cf_ns'];
		$cf_sj = $request['cf_sj'];
				
		$this->_cf('6006', $cf_ns);
		$this->_cf('8008', $cf_sj);	
		
		return true;
	}
	
	function _cf($exten, $cf) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET cf = '%s' WHERE exten = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp_exten, $cf, $exten);
		debug($sql);
		$db->query($sql);
		
		$am = $this->am($exten);		
		if (empty($cf)) {
			$am->database_del('CF', $exten);
		} else {
			$am->database_put('CF', $exten, $cf);
		}
		
		$this->am_close($am);
	}
	
	function b($controller, $request) {

		$controller->display($request, 'emp/user/b');
		return true;
	}
	
	function c($controller, $request) {

		$controller->display($request, 'emp/user/c');
		return true;
	}

	/**
	 * 找回密码
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function ajax_forget(&$controller, &$request) {
		$controller->display($request, 'emp/forget');
		return true;
	}

	/**
	 * 找回密码
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function ajax_forgetPost(&$controller, &$request) {
		$username = trim($request['username']);

		$ret = array();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE code = '%s' or name = '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, $username, $username);
		$result = $db->query($sql);
		if ($db->num_rows($result) < 1) {
			$ret['status'] = 3;
			$ret['message'] = '用户不存在，找回密码失败！';
			echo json_encode($ret);
			return true;
		}
				
		$row = $db->fetch_array($result);
		$email = $row['email'];
		if (empty($email)) {
			$email = 'sunxy@tecmold.com';
		}

		$from = $this->email;
		$subject = '景荣办公系统 - 找回密码 ';
		$fmt = "%s，您好，\n\n您已成功找回密码，新密码是：%s\n\n孙晓晔\n%s";
		$body = sprintf($fmt, $row['name'], $row['password'], date('Y-m-d H:i:s'));

		$this->sendmail($from, $email, $subject, $body);
		// echo $body;

		if ($row['email'] <> $email) {
			$ret['status'] = 2;
			$ret['message'] = "找回密码成功，请联系孙晓晔，分机6595。";
		} else {
			$ret['status'] = 1;
			$ret['message'] = "找回密码成功，请查看您的邮箱" . $email;
		}
		
		echo json_encode($ret);
		return true;
	}

	/**
	 * 景荣通讯簿
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function dept($controller, $request) {
		$this->pretreat($controller);

		$sql_office = "";
		$office = $request['office'];
		if (!empty($office)) {
			$sql_office = " AND a.office = " . $office;
		}

		$orderby = $request['orderby'];
		if (empty($orderby)) {
			$orderby = "orderby";
		}

		$q = "";

		$a = $request['a'];
		if ($request['a'] == '2') {
			$desc = "desc";
			$a = 1;
		} else {
			$desc = "";
			$a = 2;
		}
		$q .= "&a=" . $a;

		$controller->assign("q", $q);

		$ff = "name, code, sex, a.job, education, birthday, nationality, marriage, source, idcard, address, province, city, `join`, a.mobile, urgent, t1, t2, jj";
		$data = array();
		$db = newdb($this->dsn_r);
		$fmt = "SELECT %s FROM %s a WHERE status = 1 %s ORDER BY %s %s";
		$sql = sprintf($fmt, $ff, Constant::tbl_emp, $sql_office, $orderby, $desc);
		debug($sql);
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);
		
		$controller->display($request, 'emp/dept');
		return true;
	}

	function reset($controller, $request) {
		$from = $this->email;
		$subject = '景荣办公系统 - 密码重置 ';
		$content = "%s，您好，\n\n系统已重新帮您设置了一个新密码，新密码是：%s\n\n孙晓晔\n%s";	
		echo $this->sendmail('sunxy@tecmold.com', 'sunxy@tecmold.com', $subject, 'this is a test mail.测试');
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND dept = 'sc'";
		$sql = sprintf($fmt, Constant::tbl_emp);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$email = $row['email'];
			if (empty($email)) {
				continue;
			}
			echo ".";
			
			$password = rand(1000, 9999);

			$body = sprintf($content, $row['name'], $password, date('Y-m-d H:i:s'));
			$this->mail($from, $email, $subject, $body);
		}

		logdate($controller, $request);
		return true;
	}

	function mail($from, $to, $subject, $body) {
		require_once "Mail.php";
		require_once "Mail/mail.php";

		$subject = "=?utf-8?B?" . base64_encode($subject) . "?=";

		$sendmail = new Mail_mail();
		$header['Subject'] = $subject;
		$header['From'] = $from;
		$header['Content-Type'] = 'text/plain; charset=utf-8';
		$header['Content-Transfer-Encoding'] = "base64";

		$body = chunk_split(base64_encode($body));

		$sendmail->send($to, $header, $body);
	}

	function rand($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE password = '1'";
		$sql = sprintf($fmt, Constant::tbl_emp);
		// debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			$password = rand(1000, 9999);

			$fmt = "UPDATE %s SET password = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_emp, $password, $row['id']);
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function openfire($controller, $request) {
		require_once(dirname(__FILE__) . '/Mac.class.php');
		$aa = new Mac();
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE status = '1'";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$name = $row['name'];
			$email = $row['email'];
			
			$delete = false;
			if (!$aa->_exist_emp($row['id']) && empty($email)) {
				// continue;
				$delete = true;
			}
			
			$password = substr($row['idcard'], -4);
			
			$username = $this->_username($email, $name);
			
			$this->_im($username, $password, $name, $email, $delete);
		}
	
		logdate($controller, $request);
		return true;
	}
	
	function _username($email, $name) {
		$email = trim($email);
		$name = trim($name);
		
		if (empty($email)) {
			return name_account(utf82gb($name));
		}
		
		list($name, $server) = explode('@', $email);
		
		return $name;
	}
	
	function _im($username, $password, $name, $email, $delete) {
		// $creationDate = time();
		$tbl = 'openfire.ofUser';
		
		$db = newdb("openfire");
		if ($delete) {
			$fmt = "DELETE FROM %s WHERE username = '%s' and name = '%s'";
			$sql = sprintf($fmt, $tbl, $username, $name);
			
		} else {
			$fmt = "INSERT INTO %s(username, plainPassword, name, email, creationDate, modificationDate) VALUES('%s', '%s', '%s', '%s', unix_timestamp(), unix_timestamp())";
			$sql = sprintf($fmt, $tbl, $username, $password, $name, $email);	
		}
		
		echo $sql . "\n";
		$db->query($sql);
	}
	
	function mogile($controller, $request) {
		global $cfg;
	
		$t = $cfg['mogilefs']['qx'];
		
		$mg = new MogileFs();
		$mg->connect($t['host'], $t['port'], $t['domain']);
		
		$db = newdb($this->dsn_w);
		// $fmt = "SELECT * FROM %s WHERE status = '1'";
		// $fmt = "SELECT * FROM %s WHERE status <> 1";
		$fmt = "SELECT * FROM %s ";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (empty($row['photo'])) {
				continue;
			}
			
			$key = sprintf("emp_%s", $row['id']);
			
			try {
				$paths = $mg->get($key);
				$url = $paths['path1'];
			} catch(MogileFsException $e) {
				echo $e;
			}
			
			if (!preg_match("/dev202/i", $url)) {
				echo $url . "\n";
				echo "S";
				continue;
			}
			
			$row['photo_t'] = $this->_photo3($row);
			
			// print_r($row);
			
			if (preg_match('/^\//i', $row['photo_t'])) {
				$file = $cfg['upload'] . $row['photo_t'];
			} else {
			
				
				echo $row['photo_t'] . "\n";
				$buf = file_get_contents($row['photo_t']);
				
				$file = sprintf("/tmp/emp_%s", $row['id']);
				file_put_contents($file, $buf);
			}
			
			try {
				$mg->put($file, $key, $t['class']);
				// $mg->put('/Users/sunxiaoye/aa/baidu.gif', 'baidu6', 'upload');
				
				$paths = $mg->get($key);
				print_r($paths);
			
			} catch(MogileFsException $e) {
				echo $e;
			}
		}
		
		$mg->close();
	
		logdate($controller, $request);
		return true;
	}
	
	function photo($controller, $request) {
		$id = $request['id'];
		
		$mg = new MogileFs();
		$mg->connect('192.168.8.13', 7001, 'image');
		
		$key = sprintf("emp_%s", $id);
		$paths = $mg->get($key);
		
		// $buf = file_get_contents($paths['path1']);
		/*
		Header("Content-type: image/png");
		$im = imageCreateFromPng($paths['path1']);
		imagePng($im);
		ImageDestroy($im);
		*/
	}
	
	function ldap($controller, $request) {
	
		require_once(dirname(__FILE__) . '/Ldap.class.php');
		$ldap = new Ldap();
	
		$ds = $ldap->_connect();
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s limit 5";
		$fmt = "SELECT * FROM %s WHERE book = '1' AND status = '1'";
		$fmt = "SELECT * FROM %s WHERE id = '1041'";
		$fmt = "SELECT * FROM %s WHERE status = '1'";
	
		// $fmt = "SELECT * FROM %s WHERE modifytime > DATE_ADD(now(), INTERVAL -7 DAY)";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (empty($row['dept'])) {
				continue;
			}
			
			// $row['status'] = '2';
			
			$ldap->_abcd($ds, $row);
		}
	
		ldap_close($ds);
	
		logdate($controller, $request);
		return true;
	}
	
}
?>
